"""
部署模型
"""
from datetime import datetime
from sqlalchemy import Boolean, Column, DateTime, Integer, String, Text, JSON, ForeignKey
from sqlalchemy.orm import relationship

from app.core.database import Base


class Deployment(Base):
    """部署模型"""
    __tablename__ = "deployments"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(100), index=True, nullable=False)
    version = Column(String(50), nullable=False)
    status = Column(String(20), default="pending")  # pending, running, success, failed, cancelled
    deployment_type = Column(String(20), default="rolling")  # rolling, blue_green, canary
    strategy = Column(JSON)  # Deployment strategy configuration
    config = Column(JSON)  # Deployment configuration
    logs = Column(Text)  # Deployment logs
    error_message = Column(Text)  # Error message if failed
    started_at = Column(DateTime)
    completed_at = Column(DateTime)
    duration = Column(Integer)  # Duration in seconds
    created_at = Column(DateTime, default=datetime.utcnow)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 外键
    application_id = Column(Integer, ForeignKey("applications.id"), nullable=False)
    environment_id = Column(Integer, ForeignKey("environments.id"), nullable=False)
    creator_id = Column(Integer, ForeignKey("users.id"), nullable=False)
    
    # 关联关系
    application = relationship("Application", back_populates="deployments")
    environment = relationship("Environment", back_populates="deployments")
    creator = relationship("User", back_populates="deployments")
    history = relationship("DeploymentHistory", back_populates="deployment")


class DeploymentHistory(Base):
    """部署历史模型"""
    __tablename__ = "deployment_history"

    id = Column(Integer, primary_key=True, index=True)
    action = Column(String(50), nullable=False)  # deploy, rollback, scale, stop
    status = Column(String(20), nullable=False)  # success, failed
    message = Column(Text)
    config_snapshot = Column(JSON)  # Configuration snapshot
    created_at = Column(DateTime, default=datetime.utcnow)
    
    # 外键
    deployment_id = Column(Integer, ForeignKey("deployments.id"), nullable=False)
    
    # 关联关系
    deployment = relationship("Deployment", back_populates="history")
